import { objDeepCopy,getDateString } from "@/assets/js/common.js";
import commonObject from "@/assets/js/xm.js";
let Controller = {
	created() {
		this.init();
	},
	activated() {
		this.init();
	},
	mounted() {
		// console.log(this.$route.query.data)
		var linkto =  this.$route.query.to;
		//打开相应的tab和弹窗
		if(linkto == 'addPay') {
			this.toaddPay()
			this.Model.activeTab = '3';
		}else if(linkto == 'addGift') {
			this.toaddGift()
			this.Model.activeTab = '2';
		}
	},
	methods: {
		init() {
			this.Model.saleNumber = this.$route.query.saleNumber;//订单编号
			this.Model.saleId = this.$route.query.id;		//订单id
			this.getDetailList(this,this.Model.saleId);
			this.getReceptionTab(this,this.Model.saleNumber);
			
			this.getAllProvince(this);//获取省
			this.getSelfLiftCity(this);//获取全部城市
		},
		//获取详情列表
		getDetailList(that,id) {
			this.$ajax({
				method: 'get',
				url:this.apiTest+'/sale/saleOrder/'+id,
				//url:'/api/saleOrder/'+id,
			}).then((res)=>{
				var data = res.data;
				if(data.status == 200){
					var result = data.result;
					console.log(result)
					that.Model.pageOrderStatus = result.orderStatus;//整个订单状态
					that.Model.afterStatus = result.aftersaleStatus;//售后状态
					that.Model.shippingMethod = result.shippingMethod;
					that.Model.customerId = result.customerId;//新建地址时用到
					that.Model.idCard = result.idCard;//新建地址时用到
					that.Model.mobile = result.mobile;//获取收货信息时用到
					//
					let StatusWord = ['待付款','待审核','待发货','待提货','部分已发货','待收货','已完成','已关闭'];
					that.Model.tabFormInline = [
						{
							label: '订单编号',
							value: result.saleNumber,
						},
						{
							label: '订单状态',
							value: StatusWord[result.orderStatus],
						},
					]
					//步骤条
					// that.refundStep.step = objDeepCopy(result.saleOrderStatusList);
					var stepData =  objDeepCopy(result.saleOrderStatusList);
					var stepArr = [];
					for (let i = 0; i < stepData.length; i++) {
						if(stepData[i].code == result.orderStatus){
							that.Model.refundStep.activeStep = i;
						}
						let obj = {
							title:stepData[i].codeName,
							description:stepData[i].createTime,
						}
						stepArr.push(obj);
					}
					that.Model.refundStep.step = objDeepCopy(stepArr);
					//订单基础信息
					var aftersaleWord;
					//对应 售中状态
					switch (result.aftersaleStatus){
						case 42:
							aftersaleWord = '未申请'
							break;
						case 43:
							aftersaleWord = '售中变更中'
							break;
						case 44:
							aftersaleWord = '售后中'
							break;
						case 45:
							aftersaleWord = '退款中'
							break;
						case 46:
							aftersaleWord = '退货退款中'
							break;
						case 47:
							aftersaleWord = '售中变更成功'
							break;
						case 48:
							aftersaleWord = '退款成功'
							break;
						case 49:
							aftersaleWord = '售后成功'
							break;
						case 50:
							aftersaleWord = '退货退款成功'
							break;
						case 51:
							aftersaleWord = '已取消'
							break;		
						default:
							break;
					}
					let payWord = ['未支付','部分支付','已支付'];
					let shippingWord = ['快递','自提'];
					that.Model.tableFormInline = [
						{
							label: '原sap销售订单号',
							value: result.sapSaleNumber,
							disabled:true,
						},
						{
							label: '售中状态',
							value: aftersaleWord,
							disabled:true,
						},
						{
							label: '支付状态',
							value: payWord[result.payStatus],
							disabled:true,
						},
						{
							label: '首次支付时间',
							value: result.firstPayTime,
							disabled:true,
						},
						{
							label: '下单人',
							value: result.createBy,
							disabled:true,
						},
						{
							label: '配送类型',
							value: shippingWord[result.shippingMethod],
							disabled:false,
						},
						{
							label: '发货门店',
							value: result.shipperName,
							disabled:false,
						},
						{
							label: '销售来源',
							value: result.originChannel,
							disabled:true,
						},
						{
							label: '销售员',
							value: result.salesman,
							disabled:true,
						},
						{
							label: '用户备注',
							value: result.orderRemarks,
							disabled:false,
						},
						{
							label: '销售备注',
							value: result.remarks,
							disabled:false,
						}
					]
					//用户资料
					let sexualityWord = ['异性恋','女同性恋','男同性恋'];
					that.Model.tableFormUserMsg = [
						{
							label: '用户id',
							value: result.customerId,
							disabled:true,
						},
						{
							label: '客户手机号',
							value: result.mobile,
							disabled:true,
						},
						{
							label: '男士姓名',
							value: result.manName,
							disabled:true,
						},
						{
							label: '女士联系电话',
							value: result.ladiesPhone,
							disabled:true,
						},
						{
							label: '女士姓名',
							value: result.womanName,
							disabled:true,
						},
						{
							label: '恋爱属性',
							value: sexualityWord[result.sexuality],
							disabled:true,
						},
						{
							label: '男士身份证号码',
							value: result.idCard,
							disabled:true,
						},
						{
							label: '真爱日期',
							value: result.trueLoveDate,
							disabled:false,
						},
						{
							label: '专属编码',
							value: result.exclusiveCode,
							disabled:true,
						},
						{
							label: '用户期望自提时间',
							value: result.expectReceiveTime,
							disabled:false,
						}
					]
					that.Model.loveDeclaration = result.loveDeclaration;
					//订单商品明细
					result.saleOrderGoodsList[0].isAddLogoWord = result.saleOrderGoodsList.isAddLogo ? '是' : '否';
					result.saleOrderGoodsList[0].isHighWord = result.saleOrderGoodsList.isHigh ? '是' : '否';
					
					//描述换行处理
					if(result.saleOrderGoodsList[0].describe){
						var str = result.saleOrderGoodsList[0].describe;
						str=str.replace(/<br\/?>/gi,"\r\n");	
						result.saleOrderGoodsList[0].describeWord = str;
					}
		
					that.Model.tab1TableData = objDeepCopy(result.saleOrderGoodsList);
					//支付信息
					that.Model.payInfo = {
						currency:result.currency,
						commodity:[
							{
								label:'商品金额',
								value:this.Model.totleGoodPrice
							},
							{
								label:'定制费用',
								value:this.Model.totleGoodFree
							},
							{
								label:'积分抵扣',
								value:result.scoreDeduction
							},
							{
								label:'优惠券抵扣',
								value:result.couponDeduction
							},
							{
								label:'定制服务费抵扣',
								value:result.customServiceFeeDeduction
							},
							{
								label:'应收总金额',
								value:result.amountPayable
							}
						],
						total:[
							{
								label:'实收总金额',
								value:result.payAmount
							},
							{
								label:'未付款金额:',
								value:result.waittingPayment
							}
						],
					}
					//收货地址
					var opaddr = objDeepCopy(result.saleReceivingList[0]);
					that.Model.addressId = result.saleReceivingList[0].id;
					that.Model.saleAddressData =[
						{
							label:'收件人姓名',
							value:opaddr.recipientName
						},
						{
							label:'收件人手机号',
							value:opaddr.recipientPhone
						},
						{
							label:'短信通知手机',
							value:opaddr.messagePhone
						},
						{
							label:'收件地址类型',
							value:opaddr.addressType
						},
						{
							label:'收件人地区',
							value:opaddr.provinceName+opaddr.cityName+opaddr.areaName
						},
						{
							label:'详细地址',
							value:opaddr.detailedAddress
						},
					]
					that.Model.saleAddressSelfData =[
						{
							label:'自提店铺城市',
							value:opaddr.takeGoodsShopCity
						},
						{
							label:'自提门店',
							value:opaddr.takeGoodsShopName
						},
						{
							label:'自提时间',
							value:opaddr.takeGoodsTime
						},
					]
					that.Model.tab2TableData1 = objDeepCopy(result.saleOrderGiftsList);
					if(result.saleOrderGiftsList.length){
						// 附赠品列表
						that.Model.tab2TableData2 = objDeepCopy([result.saleOrderGiftsList[0].saleReceivingGoods]);
						that.Model.specialReason = that.Model.tab2TableData1[0].reason;
						//地址弹窗里的值
						that.Model.adressDialogit.id = result.saleOrderGiftsList[0].saleReceivingGoods.id;
						that.Model.adressDialogit.recipientName = result.saleOrderGiftsList[0].saleReceivingGoods.recipientName;
						that.Model.adressDialogit.recipientPhone = result.saleOrderGiftsList[0].saleReceivingGoods.recipientPhone;
						that.Model.adressDialogit.detailedAddress = result.saleOrderGiftsList[0].saleReceivingGoods.detailedAddress;
					}
					//tab3
					that.Model.tab3TableData1 = objDeepCopy(result.saleOrderPayList);
					that.Model.tab3TableData2 = objDeepCopy(result.refundList);
					//tab6
					that.Model.tab6TableData = objDeepCopy(result.saleReOrderList);
					//tab7
					that.Model.tab7TableData =  objDeepCopy(result.saleInOrderList);
					//tab8
					that.Model.tab8TableData =  objDeepCopy(result.saleOutOrderList);
					//tab 9 操作日志
					that.Model.tab9TableData = objDeepCopy(result.saleLogList);
				}else{
					that.tips(that,'warning',data.msg)
				}
			    
			});
		},
		//获取tab7（接待记录）
		getReceptionTab(that,orderId) {
			this.$ajax({
			  method: 'get',
			  url:this.apiTest+'/crm/reservationInfo/sale/getDetail?orderId='+orderId,
			  // url:'/api/crm/reservationInfo/sale/getDetail?orderId='+orderId,
			}).then((res)=>{
				var data = res.data;
				if(data.status == 200){
					var result = data.result;
					that.Model.tab5TableData = objDeepCopy(result);
					//
				}else{
					that.tips(that,'warning',data.msg)
				}
			    
			});
		},
		//审核
		Approval() {
			var that = this;
			var saleId = Number(this.Model.saleId);
			this.$ajax({
			  method: 'get',
			  url:this.apiTest+'/sale/saleOrder/check/'+saleId,
			}).then((res)=>{
				var data = res.data;
				if(data.status == 200){
					var result = data.result;
					that.tips(that,'success','操作成功');
					that.getDetailList(that,saleId);
					//
				}else{
					that.tips(that,'warning',data.msg);
				}
			    
			});
		},
		//获取地址信息（身份证或者电话）
		getaddressList(that){
			var apiTest = this.apiTest;
			//
			var idCard = this.Model.idCard;
			var mobile = this.Model.mobile;
			this.$ajax({
			  method: 'post',
			  url:apiTest+'/crm/customerInfo/sale/findReceiverInfo',
			  // url:'/api/saleOrderGoods/findChangeRecordGoods/1',
			  data:{
				idCard:idCard,
				phone:mobile
			  }
			}).then((res)=>{
				var data = res.data
				if(data.status == 200){
					var result = data.result;
					if(result){
						that.Model.addressInfoList = objDeepCopy(result.receiverInfoList);
					}
				}else{
					that.tips(that,'warning',data.msg)
				}
			    
			});
		},
		//点击修改地址打开弹窗
		openDialogAddress() {
			this.Model.onDialogAddress = true;
			//
			this.getaddressList(this);
		},
		//修改地址请求
		changeSAddressAjax(that,params){
			var apiTest = this.apiTest;
			//
			this.$ajax({
			  method: 'put',
			  url:apiTest+'/sale/saleReceivingGoods',
			  // url:'/api/saleOrderGoods/findChangeRecordGoods/1',
			  data:params
			}).then((res)=>{
				var data = res.data
				if(data.status == 200){
					var result = data.result;
					if(result == 1){
						that.tips(that,'success','修改地址成功');
						that.getDetailList(that,that.Model.saleId);
						setTimeout(function(){
							that.Model.onDialogAddress = false;
							that.Model.onDialogself = false;
						},1000)
					}
				}else{
					that.tips(that,'warning',data.msg)
				}
			    
			});
		},
		
		//修改地址 保存
		saleAddressSave() {
			var userAddressMsg = this.Model.userAddressMsg;		//新建的地址option
			var checkedAddressOpt = this.Model.checkedAddressOpt;		//修改地址的option
			var id = this.Model.addressId;
			var saleOrderId = this.Model.saleId;
			var params;
			var customerId = this.Model.customerId;
			var idCard = this.Model.idCard;
			if(userAddressMsg.isNewAddress){
				params = {
					id:id,
					saleOrderId:saleOrderId,
					customerId:customerId,
					idCard:idCard,
					recipientName:userAddressMsg.recipientName,
					recipientPhone:userAddressMsg.recipientPhone,
					messagePhone:userAddressMsg.messagePhone,
					addressType:userAddressMsg.addressType,
					countryCode:userAddressMsg.countryCode,
					countryName:userAddressMsg.countryName,
					provinceCode:userAddressMsg.provinceCode,
					provinceName:userAddressMsg.provinceName,
					cityCode:userAddressMsg.cityCode,
					cityName:userAddressMsg.cityName,
					areaCode:userAddressMsg.areaCode,
					areaName:userAddressMsg.areaName,
					detailedAddress:userAddressMsg.detailedAddress
				}
				
			}else{
				params = {
					id:id,
					saleOrderId:saleOrderId,
					recipientName:checkedAddressOpt.name,
					recipientPhone:checkedAddressOpt.phone,
					messagePhone:userAddressMsg.messagePhone,//messagePhone 自己填寫
					addressType:checkedAddressOpt.addressType,
					countryCode:checkedAddressOpt.countryCode,
					countryName:'中国',
					provinceCode:checkedAddressOpt.geographyProvince.countryCode,
					provinceName:checkedAddressOpt.geographyProvince.provinceName,
					cityCode:checkedAddressOpt.geographyCity.cityCode,
					cityName:checkedAddressOpt.geographyCity.cityName,
					areaCode:checkedAddressOpt.geographyArea.areaCode,
					areaName:checkedAddressOpt.geographyArea.areaName,
					detailedAddress:checkedAddressOpt.address
				}
			}
			this.changeSAddressAjax(this,params);
			
		},
		// 自提 点击保存
		saleaddressSelfSave() {
			var userSelfLift = this.Model.userSelfLift;
			var id = this.Model.addressId;
			var saleOrderId = this.Model.saleId;
			var params = {
				id:id,
				saleOrderId:saleOrderId,
				takeGoodsShopCity:userSelfLift.takeGoodsShopCity,
				takeGoodsShop:userSelfLift.takeGoodsShop,
				takeGoodsTime:userSelfLift.time,
			}
			console.log(params)
			this.changeSAddressAjax(this,params);
		},
		// 点击确认保存修改
		saleOrderSave() {
			var param;
			var type = this.Model.editDialogType;
			var data = this.Model.editDialogFormData;
			var saleId = this.Model.saleId;
			if(type == 'tableFormInline'){
				param = {
					id:saleId,
					shippingMethod:data[5].value,
					shipper:data[6].value,
					remarks:data[10].value,
					orderRemarks:data[9].value
				}
			}else if(type == 'tableFormUserMsg'){
				param = {
					id:saleId,
					loveDeclaration:data[9].value,
					trueLoveDate:data[7].value,
					expectReceiveTime:data[10].value,
				}
			}else{
				
			}
			this.changeSaleOrder(this,param);
		},
		//点击加急
		onItemExpedited(row){
			var that = this;
			this.$ajax({
				method: 'put',
				url:this.apiTest+'/sale/saleOrderGoods',
				data:{
					id:row.id,
					isUrgent:true,
				}
			}).then((res)=>{
				var data = res.data;
				if(data.status == 200){
					that.tips(that,'success','加急成功')
					this.getDetailList(this,this.Model.saleId);
					//
				}else{
					that.tips(that,'warning',data.msg)
				}
			    
			});
		},
		//获取省
		getAllProvince(that) {
			this.$ajax({
				method: 'get',
				url:this.apiTest+'/crm/geographyProvince/queryProvinceList?language=1&countryCode=CN',
				// url:'/api/crm/geographyProvince/queryProvinceList?language=1&countryCode=CN',
			}).then((res)=>{
				 var data = res.data;
				 if(data.status == 200){
					 that.options = [];
						var result = data.result;
						for(var i  = 0; i < result.length; i++){
							var obj = {
									code: result[i].provinceCode,
									label: result[i].provinceName,
									children:[]
							}
							that.Model.options.push(obj);
						}
				 }else{
						
				 }
					
			});
		},
		//获取市
		getAllCity(that,provinceCode) {
			this.$ajax({
				method: 'get',
				url:this.apiTest+'/crm/geographyCity/queryCityList?language=1&countryCode=CN&provinceCode='+provinceCode,
				// url:'/api/crm/geographyCity/queryCityList?language=1&countryCode=CN&provinceCode='+provinceCode,
			}).then((res)=>{
				 var data = res.data;
				 if(data.status == 200){
						var result = data.result;
						var options = that.Model.options;
						var cities = [];
						//遍历数据
						for(var i  = 0; i < result.length; i++){
							var obj = {
									code: result[i].cityCode,
									label: result[i].cityName,
									children:[]
							}
							cities.push(obj);
						}
						//查找 相对应的省
						for(var i  = 0; i < options.length; i++){
							if(options[i].code == provinceCode){
								options[i].children  = objDeepCopy(cities);
							}
						}
				 }else{
						
				 }
					
			});
		},
		//获取区（县）
		getAllCounty(that,provinceCode,cityCode) {
			this.$ajax({
				method: 'get',
				url:this.apiTest+'/crm/geographyArea/queryAreaList?language=1&countryCode=CN&provinceCode='+provinceCode+'&cityCode='+cityCode,
				// url:'/api/crm/geographyArea/queryAreaList?language=1&countryCode=CN&provinceCode='+provinceCode+'&cityCode='+cityCode,
			}).then((res)=>{
				 var data = res.data;
				 if(data.status == 200){
						var result = data.result;
						var areas = [];
						var options = that.Model.options;
						//遍历数据
						for(var i  = 0; i < result.length; i++){
							var obj = {
									code: result[i].areaCode,
									label: result[i].areaName
							}
							areas.push(obj);
						}
						//查找 相对应的区（县）
						for(var i  = 0; i < options.length; i++){
							if(options[i].code == provinceCode){
								var cities = options[i].children;
								for(var j  = 0; j < cities.length; j++){
									if(cities[j].code == cityCode){
										cities[j].children  = objDeepCopy(areas);
									}
								}
							}
						}
				 }else{
						
				 }
					
			});
		},
		// 获取自提城市
		getSelfLiftCity(that) {
			var apiTest = this.apiTest;
			this.$ajax({
				method: 'get',
				url:apiTest+'/crm/geographyCity/queryCityList?language=1&countryCode=CN',
			}).then((res)=>{
				var data = res.data;
				if(data.status == 200){
					var result = data.result;
					that.Model.allCities = objDeepCopy(result);
				}else{
					that.tips(that,'warning',data.msg)
				}
			    
			});
		},
		//获取 门店
		getSupplierShop(that,city) {
			var apiTest = this.apiTest;
			this.$ajax({
				method: 'post',
				url:apiTest+'/supplier/supplierShop/getList',
				data:{
					city:city
				}
			}).then((res)=>{
				var data = res.data;
				if(data.status == 200){
					var result = data.result;
					if(result){
						that.Model.cityStore = objDeepCopy(result);
					}
					
				}else{
					that.tips(that,'warning',data.msg)
				}
			    
			});
		},
		//切换城市 获取门店信息
		queryStore(value) {
			this.getSupplierShop(this,value);
		},
		//切换省市区
		handleItemChange(val) {
			console.log(val)
			if(val.length == 1){
				var provinceCode = val[0];
				this.getAllCity(this,provinceCode);
			}else if(val.length == 2){
				var provinceCode = val[0];
				var cityCode = val[1];
				this.getAllCounty(this,provinceCode,cityCode)
			}else{
				
			}
		},
		//联机选择器 选择结束触发
		changecascards(val) {
			var labelStr = '';
			var cascaderArr = this.getCascaderObj(val, this.Model.options);
			for (let i = 0; i < cascaderArr.length; i++) {
				labelStr += cascaderArr[i].label;
			}
			this.Model.userAddressMsg.countryCode = 'CN';
			this.Model.userAddressMsg.countryName = '中国';
			this.Model.userAddressMsg.provinceCode = cascaderArr[0].code;
			this.Model.userAddressMsg.provinceName = cascaderArr[0].label;
			this.Model.userAddressMsg.cityCode = cascaderArr[1].code;
			this.Model.userAddressMsg.cityName = cascaderArr[1].label;
			this.Model.userAddressMsg.areaCode = cascaderArr[2].code;
			this.Model.userAddressMsg.areaName = cascaderArr[2].label;
			console.log(cascaderArr)
		},
		//遍历 得到label及value
		getCascaderObj(val,opt){
			return val.map(function (value, index, array) {
		        for (var item of opt) {
		            if (item.code == value) {
						opt = item.children;
						return item;
					}
		        }
		        return null;
		    });
		},
		//发起退款
		refund(that,param) {
			this.$ajax({
				method: 'post',
				url:this.apiTest+'/sale/saleOrder/refund',
				data:param
			}).then((res)=>{
				var data = res.data;
				if(data.status == 200){
					that.tips(that,'success','发起退款成功')
					this.getDetailList(this,this.Model.saleId);
					setTimeout(function(){
						that.Model.orderAfterDialog = false;
					},1000);
					//
				}else{
					that.tips(that,'warning',data.msg)
				}
			    
			});
		},
		//点击发起退款 按钮
		onItemRefund(row) {
			var saleId = Number(this.Model.saleId)
			var param = {
				saleOrderId:saleId, //销售订单id
				userId:-1, //登录人id
				goodsId:row.id, //商品id
				afterSaleType:20
			}
			this.refund(this,param)
		},
		//点击查看售中 售后 变更记录
		onItemChangeLog(row) {
			this.Model.orderChangeDialog = true;
			this.Model.orderChangeDialo = true;
			this.Model.tab1ChangeTableData = [];
			this.$ajax({
				method: 'get',
				url:this.apiTest+'/sale/saleOrderGoods/findChangeRecordMasterGoods/'+row.id,
				// url:this.apiTest+'/sale/saleOrder/findChangeRecordGoods/5239',
			}).then((res)=>{
				var data = res.data;
				if(data.status == 200){
					var obj = {};
					var result = data.result;
					console.log(result)
					for (var i = 0; i < result.length; i++) {
						obj = objDeepCopy(result[i]);
						
						//
						this.Model.tab1ChangeTableData.push(obj);
					}
				}else{
					this.tips(this,'warning',data.msg);
				}
			    
			});
		},
		
		//确认 发起售后操作 
		comfirmAfter(){
			var row = this.Model.tab1Row;
			var saleId = Number(this.Model.saleId)
			var param = {
				saleOrderId:saleId, //销售订单id
				userId:-1, //登录人id
				goodsId:row.id, //商品id
				afterSaleType:30,
			}
			var paramOther = {
				tableData: [row],
				tableFormInline: this.Model.tableFormInline,
				id:saleId,
				originId:row.id,				
			}
			switch (this.Model.afterType){
				case '1':
					this.refund(this,param)
					break;
				case '2':
					paramOther.afterSaleType=40;
					this.$router.push({
						name: 'afterOrderOnChange',
						query: {
							data:JSON.stringify(paramOther)
						}
					})
					this.Model.orderAfterDialog = false;
					break;
				case '3':
					paramOther.afterSaleType=30;
					this.$router.push({
						name: 'afterOrderOnChange',
						query: {
							data:JSON.stringify(paramOther)
						}
					})
					this.Model.orderAfterDialog = false;
					break;
				default:
					break;
			}
		},
		//跳转到crm列表详情
		toCrmDetial(row) {
			this.$router.push({
				name: 'seeDetailAll',
				query: {
					searchKey: row.id
				}
			})
		},	
		//发起变更 
		onOrderChange(row) {
			const param = {
				tableData: [row],
				tableFormInline: this.Model.tableFormInline,
				id: this.Model.saleId,
				originId: row.id,
				afterSaleType: 10
			}
			this.$router.push({
				name: 'orderOnChange',
				query: {
					data:JSON.stringify(param)
				}
			})
		},
		//发起售后
		onOrderAfter(row) {
			this.Model.orderAfterDialog = true;
			this.Model.tab1Row = row;
		},
		//支付操作 作废
		payObsolete(row) {
			var that = this;
			this.$confirm('是否确认作废?', '提示', {
			  confirmButtonText: '确定',
			  cancelButtonText: '取消',
			}).then(() => {
				that.$ajax({
					method: 'put',
					url:this.apiTest+'/sale/saleOrderPay',
					data:{
						id:row.id,
						payStatus:2
					}
				}).then((res)=>{
					var data = res.data;
					if(data.status == 200){
						that.tips(that,'success','支付记录作废成功');
						that.getDetailList(that,that.Model.saleId);
					}else{
						that.tips(that,'warning',data.msg);
					}
					
				});
			}).catch(() => {
			  
			});
		},
		//赠品编辑地址
		adressEdit(val) {
			this.Model.adressDialog = true;
		},
		//确认修改地址
		ToSaveadress() {
			var pramas = this.Model.adressDialogit;
			var that = this;
			console.log(pramas)
			this.$ajax({
				method: 'put',
				url:this.apiTest+'/sale/saleReceivingGoods',
				data:pramas
			}).then((res)=>{
				var data = res.data;
				if(data.status == 200){
					that.tips(that,'success','操作成功');
					this.getDetailList(this,this.Model.saleId);
					setTimeout(function(){
					  that.Model.adressDialog = false;
					},1000)
				}else{
					that.tips(that,'warning',data.msg);
				}
			    
			});
		},
		//获取赠品列表
		getGiftlists(that,params) {
			params = params || {}
			this.$ajax({
				method: 'post',
				url:this.apiTest+'/sale/saleGoodsMaster/findGiftsList',
				data:params
			}).then((res)=>{
				that.Model.tableDataDialog = [];
				var data = res.data;
				if(data.status == 200){
					var obj = {};
					var result = data.result.result;
					for (let i = 0; i < result.length; i++) {
						obj = objDeepCopy(result[i]);
						console.log(obj);
						//
						that.Model.tableDataDialog.push(obj);
					}
				}else{
					that.tips(that,'warning',data.msg);
				}
			    
			});
		},
		//新增赠品
		toaddGift() {
			this.Model.addGiftDialog = true;
			var params;
			this.getGiftlists(this,params);
		},
		//确认添加
		sureAddgift() {
			var selectData = this.Model.addGiftsSelectData;
			var reason = this.Model.addGiftDialogit.reason;
			var obj = {};
			var params = [];
			for (let i = 0; i < selectData.length; i++) {
				obj = {
					saleOrderId:this.Model.saleId,
					giftNumber:selectData[i].commodityCode,
					giftName:selectData[i].nameOfCommodity,
					count:1,
					reason:reason
				}
				params.push(obj);
			}
			console.log(params)
			this.addGiftsAjax(this,params);
		},
		//添加赠品 请求操作
		addGiftsAjax(that,params){
			params = params || {}
			this.$ajax({
				method: 'post',
				url:this.apiTest+'/sale/saleOrderGifts/batch',
				data:params
			}).then((res)=>{
				var data = res.data;
				if(data.status == 200){
					that.tips(that,'success','添加赠品成功');
					setTimeout(function(){
						that.getDetailList(that,that.Model.saleId);
						that.Model.addGiftDialog = false;
					},1000)
				}else{
					that.tips(that,'warning',data.msg);
				}
				
			});
		},
		//删除赠品
		deleteGift(row) {
			var that = this;
			this.$confirm('是否确认删除?', '提示', {
			  confirmButtonText: '确定',
			  cancelButtonText: '取消',
			}).then(() => {
				that.$ajax({
					method: 'DELETE',
					url:this.apiTest+'/sale/saleOrderGifts/'+row.id
				}).then((res)=>{
					var data = res.data;
					if(data.status == 200){
						that.tips(that,'success','删除赠品成功');
						that.getDetailList(that,that.Model.saleId);
						setTimeout(function(){
							that.Model.addGiftDialog = false;
						},1000)
					}else{
						that.tips(that,'warning',data.msg);
					}
					
				});
			}).catch(() => {
			  
			});
			
			
		},
		//新增收款记录
		toaddPay() {
			this.Model.dialogFormVisible = true;
		},
		//确认收款记录
		comfirmPay() {
			var that = this;
			var params = this.Model.dialogForm;
			params.createTime = getDateString(params.createTime);
			params.saleOrderId = Number(this.Model.saleId);
			//params.saleOrderId = '5304';
			this.$ajax({
				method: 'post',
				url:this.apiTest+'/sale/saleOrderPay',
				data:params
			}).then((res)=>{
				console.log(res);
				var data = res.data;
				if(data.status == 200){
					//that.getDetailList(this,5304);
					that.getDetailList(that,that.Model.saleId);
					that.tips(that,'success','操作成功');
					setTimeout(function(){
						that.Model.dialogFormVisible = false;
					},1000)
				}else{
					that.tips(that,'warning',data.msg);
				}
			});
		},
		//合计
		getSummaries(param) {
			var that = this;
			const { columns, data } = param;
			const sums = [];
			columns.forEach((column, index) => {
		    if (index === 0) {
		      sums[index] = '总价';
		      return;
		    }else if(index === 5 || index === 6 || index === 7 || index === 8) {
					  const values = data.map(item => Number(item[column.property]));
					  sums[index] = values.reduce((prev, curr) => {
					    const value = Number(curr);
					    if (!isNaN(value)) {
					      return prev + curr;
					    } else {
					      return prev;
					    }
                      }, 0);
                      //商品金额
                      this.Model.totleGoodPrice = sums[7];
                      //定制费
                      this.Model.totleGoodFree = sums[6];
                      //数量
                      this.Model.totleGoodCount = sums[8];
					  /*if(index === 10){
						that.Model.totleGoodCount = sums[10];
					  }else{
						
                      }*/
                      
					  
				  }else{
					sums[index] = '/';
				  }
		  });
		
		  return sums;
		},
		selectedHighlight(data) {
			// 如果选中则添加高亮样式
			if (this.Model.TableSelectData.indexOf(data.row) > -1) {
				return {
					"background-color": "#FEF6EE"
				};
				return {}
			}
		},
		onDialogEdit(flag, val) {
			this.Model.editDialogFlag = flag;
			var saleId = this.Model.saleId;	
			if (flag === false) return;
			const arr = this.Model[val];
			this.Model.editDialogType = val;
			this.Model.editDialogFormData = _.cloneDeep(arr);
		},
		warehousing(row) {
			this.Model.warehousingDialogStatus = row.status;
			this.Model.warehousingDialogFlag = true;
		},
		handleSelectionChange(val) {
			this.Model.addGiftsSelectData = val
			this.Model.TableSelectData = val;
		},
		handleCurrentChange(val) {
			let params = this.Model.Searchparams;
			this.getProductList(this,params,val);
		},
		handleSizeChange(val) {
			let params = this.Model.Searchparams;
			this.getProductList(this,params,undefined,val);
		},
		cardClick(color) {
			this.Model.cardSelected = color;
		},
		toSearch(val) {
			var params = {
				condition:this.Model.searchFromData
			}
			console.log(params)
			this.getGiftlists(this,params)
		},
		toClear(val) {
		  this.Model.searchFromData = this.Model.defaultSearchFromData;
		},
		toExport(val) {
			console.log(val);
		},
		onTabChange(val) {
			console.log(val, this.Model.activeTab)
			switch (val) {
				case 1:
				break;
				case 2:
				break;
				case 3:
				break;
			}	
		},
		toggleTableDetail(val) {
			const obj = this.Model[val];
			if (obj.flag === true) {
				this.Model[val].src = require('@/assets/img/icon_collapse.png');
				this.Model[val].flag = false;
			} else {
				this.Model[val].src = require('@/assets/img/icon_unfold.png');
				this.Model[val].flag = true;
			}
		},
		//保存
		ToSave() {
			var param;
			var type = this.Model.editDialogType;
			var data = this.Model.editDialogFormData;
			var saleId = this.Model.saleId;
			if(type == 'tableFormInline'){
				param = {
					id:saleId,
					shippingMethod:data[5].value,
					shipper:data[6].value,
					remarks:data[10].value,
					orderRemarks:data[9].value
				}
			}else if(type == 'tableFormUserMsg'){
				param = {
					id:saleId,
					loveDeclaration:data[9].value,
					trueLoveDate:data[7].value,
					expectReceiveTime:data[10].value,
				}
			}else{
				
			}
			this.changeSaleOrder(this,param);
		},
		//切换快递自提
		selectDeliveryType(val) {
			console.log(val)
			//0 快递 1 自提
			this.Model.tipsDeliveryType = true;
			if(val == 0){
				
			}else{
				
			}
		},
		// 修改订单数据
		changeSaleOrder(that,param){
			this.$ajax({
			  method: 'put',
			  url:this.apiTest+'/sale/saleOrder',
			  data:param
			}).then((res)=>{
				var data = res.data;
				if(data.status == 200){
					that.tips(that,'success','修改成功')
					that.getDetailList(that,that.Model.saleId);
					setTimeout(function(){
						that.Model.editDialogFlag = false;
					},1000)
				}else{
					that.tips(that,'warning',data.msg)
				}
			    
			});
		},
		//编辑商品
		toggleDialog() {
			this.Model.changeGoodsDialogFlag = true;
			this.getSalesClassify();
			this.getAllSeries(this);
		},
		onSelectChange(type){
			const data = this.Model.sliderSelect[type];
			this.Model.sliderSelect[type].sliderVal = [data.value,data.value];
		},
		//获取销售分类
		getSalesClassify() {
			this.$ajax({
				method: 'post',
				url:this.apiTest+'/sale/saleGoodsAttribute/getGoodsAttributelist',
				//url:'/api/sale/saleGoodsAttribute/getGoodsAttributelist',
				data:{
					attributeCode:"M05"
				}
			}).then((res)=>{
				var data = res.data;				
				if(data.status == 200){
					var result = data.result;
					var arr = [];
					for(var i  = 0; i < result.length; i++){
						arr.push({
							label:result[i].attributeValueName,
							value:result[i].attributeValueCode
						});
					}
					this.Model.filterOption2.items[0].data = objDeepCopy(arr);
				}else{
					this.tips(this,'warning',data.msg)
				}
			    
			});
		},
		//获取系列
		getAllSeries(that) {
			//获取所有系列
			this.$ajax({
				method: 'post',
				url:this.apiTest+'/sale/saleGoodsAttribute/getGoodsAttributelist',
				//url:'/api/sale/saleGoodsAttribute/getGoodsAttributelist',
				data:{
					attributeCode:"M04"
				}
			}).then((res)=>{
				var data = res.data;		
				if(data.status == 200){
					var result = data.result;
					var arr = [];
					for(var i  = 0; i < result.length; i++){
						arr.push({
							label:result[i].attributeValueName,
							value:result[i].attributeValueCode
						});
					}
					that.Model.filterOption2.items[1].data = objDeepCopy(arr);
				}else{
					this.tips(this,'warning',data.msg)
				}
			});
		},
		//输入系列修改款式名称
		changeStyleName(that,prams,option){
			prams = prams || {}
			this.$ajax({
		        method: 'post',
		        url:this.apiTest+'/sale/saleGoodsStyle/findStyleASeriesOf/'+prams,
				//url:'/api/sale/saleGoodsStyle/findStyleASeriesOf/'+prams,
		        data:{
		        	
		        }
		  	}).then((res)=>{
		        var data = res.data;
		        if(data.status == 200){
		        	var arr = [];
		        	var result = data.result;
		        	for (var i = 0; i < result.length; i++) {
						arr.push({
							label:result[i].modelName,
							value:result[i].id
						});
		        	}
					option[2].data = objDeepCopy(arr);
					that.Model.filterOption2.items = option;
		        }else{
					this.tips(this,'warning',data.msg)
		        }
		
		    });
		},
		//获取第二步数据
		getParameters(that,prams,option) {
			this.$ajax({
				method: 'get',
				url:this.apiTest+'/sale/saleGoodsStyle/condition/'+prams,
				//url:'/api/sale/saleGoodsStyle/condition/'+prams,
				data:{
					
				}
			}).then((res)=>{
				var data = res.data;	
				if(data.status == 200){				
					var result = data.result;
					console.log(result)
					//材质
					this.Model.filterOption3.items[3].data = result.attrMap.M15.map(item => {
						return {
							label: item.attributeValueName,
							value: item.attributeValueCode
						}
					});
					//手寸
					this.Model.filterOption3.items[4].data = result.handInchList.map(item => {
						return {
							label: item,
							value: item
						}
					});
					//净度
					this.Model.filterOption3.items[5].data = result.attrMap.M10.map(item => {
						return {
							label: item.attributeValueName,
							value: item.attributeValueCode
						}
					});
					//对称
					this.Model.filterOption3.items[6].data = result.attrMap.M13.map(item => {
						return {
							label: item.attributeValueName,
							value: item.attributeValueCode
						}
					});
					//抛光
					this.Model.filterOption3.items[7].data = result.attrMap.M12.map(item => {
						return {
							label: item.attributeValueName,
							value: item.attributeValueCode
						}
					});
					//链长
					this.Model.filterOption3.items[8].data = result.attrMap.M17.map(item => {
						return {
							label: item.attributeValueName,
							value: item.attributeValueCode
						}
					});
					//颜色
					this.Model.filterOption3.items[9].data = result.attrMap.M09.map(item => {
						return {
							label: item.attributeValueName,
							value: item.attributeValueCode
						}
					});
					//切工
					this.Model.filterOption3.items[10].data = result.attrMap.M11.map(item => {
						return {
							label: item.attributeValueName,
							value: item.attributeValueCode
						}
					});
					var weightMin = result.range.fromTheRabbet*100;//钻重最小值
					var weightMax = result.range.theRabbet*100;//钻重最小值
					this.Model.weightMin=weightMin;
					this.Model.weightMax=weightMax;
					var weightArr =[];
					for (var i = weightMin; i < weightMax+1; i++) {				
						weightArr.push(i);
					}
					//钻重
					this.Model.sliderSelect = {
						weight:{
							value:'',
							option:weightArr.map(item => {
								return {
									label: item,
									value: item
								}
							}),
							sliderVal:[weightMin,weightMax],
							
						}
					}
				}else{
					this.tips(this,'warning',data.msg)
				}
			    
			});
			
		},
		//商品售价列表
		getProductList(that,params,pageIndex = 1,pageSize = 10) {
			params = params || {}
			this.$ajax({
				method: 'post',
				url:this.apiTest+'/sale/saleOrder/customListBySearch',
				//url:'/api/sale/saleOrder/customListBySearch',
				data:{
					condition:params,
					pageIndex: pageIndex,
					pageSize: pageSize,
				}
			}).then((res)=>{
				var data = res.data;	
				that.Model.tableDataDialog = [];
				if(data.status == 200){
					var obj = {};
					var pagination = commonObject.paginationFunction(data.result);
					that.Model.paginationObject = objDeepCopy(pagination);
					var result = data.result.result;
					console.log(data)
					for (var i = 0; i < result.length; i++) {				
						that.Model.tableDataDialog.push(result[i]);
					}
				}else{
					this.tips(this,'warning',data.msg)
				}
			    
			});
		},
		//点击确认添加商品
		addShop() {
			var commodityObject = this.Model.dialogTableChecked;
			
			if(commodityObject.length == 0){
				this.tips(this,'warning','请勾选数据');
			}else{
				console.log(commodityObject)
				this.getPrice(this,commodityObject);
			}
			
		},
		//点击行 选中单选框
		handleRowClick(row){
			this.Model.dialogTableChecked = row;
		},
		//获取商品的价格
		getPrice(that,commodityObject){
			var idData = this.Model.idData;
			that.Model.commodityObject= {};
			this.$ajax({
				method: 'post',
				url:this.apiTest+'/sale/saleOrder/getCustomGoods',
				//url:'/api/sale/saleOrder/getCustomGoods',
				data:commodityObject
			}).then((res)=>{
				 var data = res.data;
				 if(data.status == 200){
					var result = data.result;
					result.count = 1;
					result.isExpedited = false;  //加急
					result.isNeedWordArt = this.Model.shouldLettering; //是否需要艺术字
					result.isAddLogo = this.Model.isLogo; //外圈是否加DR LOGO
					result.isHigh = this.Model.isHighClass; //是否允许高配
					result.isAddLogoWord = this.Model.isLogo ? '是' : '否'; //外圈是否加DR LOGO（文字）
					result.isHighWord = this.Model.isHighClass ? '是' : '否'; //是否允许高配（文字）
					result.lettering = this.Model.letteringContent; //刻字
					result.customGoodsVo = commodityObject;
					/*if(idData.indexOf(result.id) == -1){
						that.Model.idData.push(result.id);
						that.Model.tableData.push(result);
						console.log(result)
						that.Model.changeGoodsDialogFlag = false;	
					}else{
						that.tips(that,'warning','该已添加');
					}*/
					//that.Model.tab1TableData.push(result);
					that.Model.tab1TableData =[result];
					that.Model.changeGoodsDialogFlag = false;	
					//				
				 }else{
					that.tips(that,'warning',data.msg);
				 }
					
			});
		},
		//新增商品里的查询
		toSearchNotSureBarCode(val) {
			let slider = this.Model.sliderSelect.weight.sliderVal;
			let params = objDeepCopy(this.Model.searchFromData3);
			params.salesType = this.Model.searchObj.origin;
			params.styleId = this.Model.searchObj.modelName;
			params.startInsert = slider[0]/100;
			params.endInsert = slider[1]/100;
			console.log(params);
			this.Model.Searchparams = params;
			this.getProductList(this,params)
			/*this.Model.tab1TableDetail1.flag = true;*/
		},
		//新增商品里获取下拉框的事件
		showChild(val,changeOb,option) {
			switch (changeOb.key) {
				case 'series':
					var prams = val.series;
					this.changeStyleName(this,prams,option);
				break;
				case 'modelName':
					var prams = val.modelName;
					//获取第二步数据
					this.getParameters(this,prams,option);
				break;	
			}
			this.Model.searchObj = objDeepCopy(val);
		},
		showNotSureBarCodeP2(val) {
			this.Model.searchFromData3 = val;
		},
		
		//售中单号跳转
		toInsaleDetial(row) {
			let name;
			switch (row.afterSaleType) {
				/* （10售中变更 20退款 30升级换款 40常规售后） */
				case 10:
					name = 'orderDetailChange'; //售中变更-跳变更页
					break;
				case 20:
					name = 'orderDetailRefund'; //退款-跳退款页
					break;
				default:
					break;
			}
			if (name) {
				this.$router.push({
					name: name,
					query: {
						data: JSON.stringify(row)
					}
				})
			}
		},
		//售后单号跳转
		toAftersaleDetial(row) {
			let name;
			switch (row.afterSaleType) {
				/* （30售后升级换款 40常规售后 50售后退款） */
				//30,40跳变更,50跳退款
				case 30:
					name = 'afterOrderDetailChange';
					break;
				case 40:
					name = 'afterOrderDetailChange';
					break;
				case 50:
					name = 'afterOrderDetailRefund';
					break;
				default:
					break;
			}
			if (name) {
				this.$router.push({
					name: name,
					query: {
						data: JSON.stringify(row)
					}
				})
			}
		},
		//新建补购
		newRepurchase() {
			this.$router.push({
				path: 'customizeCreateOrder',
				query: {
		
				}
			});
		},
		tips(that,type,message) {
			that.$message({
				message: message,
				type: type
			});
		},
	},
	watch:{
		//
		$route:{
	　　　	handler(newValue, oldValue) {
				if(newValue.query.id) {
					this.getDetailList(this,newValue.query.id);
				}
				//打开相应的tab和弹窗
				if(newValue.query.to == 'addPay') {
					this.toaddPay()
					this.Model.activeTab = '3';
				}else if(newValue.query.to == 'addGift') {
					this.toaddGift()
					this.Model.activeTab = '2';
				}
			},
	　　　	deep: true
		},
	},
	filters:{
		//sap过账
		spaPostingFilter:function(value){
			var val;
			switch (value){
				case 0:
					val = '未过帐'
					break;
				case 1:
					val = '已过账'
					break;
				default:
					break;
			}
			return val;
		},
		//支付方式
		paymentMethodFilter:function(value){
			var val;
			switch (value){
				case 1:
					val = '支付宝及时到账'
					break;
				case 2:
					val = '银联支付'
					break;
				case 3:
					val = '现金'
					break;
				case 4:
					val = '拉卡拉POS机'
					break;
				case 5:
					val = '中信银联POS机'
					break;
				default:
					break;
			}
			return val;
		},
		// 财务确认
		financeFilter:function(value){
			var val;
			switch (value){
				case 0:
					val = '未确认'
					break;
				case 1:
					val = '确认'
					break;
				default:
					break;
			}
			return val;
		},
		// 地址类型
		addressTypeFilter:function(value){
			var val;
			switch (value){
				case 0:
					val = '大陆'
					break;
				case 1:
					val = '海外'
					break;
				default:
					break;
			}
			return val;
		},
	}
}
export default Controller;
